package cn.tedu.serializable;
/**
 * @Author 金帮嘉诚   @Date 2021-06-18 周五 10:42
 */
/*本类用于测试*/

import java.io.*;

/**
 * 知识点：
 */
public class TestSerializable {
    public static void main(String[] args) {
        //序列化反序列化 UID要一致
        //改变类中属性方法时 UID会自动更改
        //如果我们手动添加了UID（long类型），只要这个值不修改，不论编译次数，UID都不会更改

        method1();
        method2();
    }

    //反序列化
    private static void method2() {
        ObjectInputStream in=null;

        try {
//            in=new ObjectInputStream(new FileInputStream(new File("d:\\ready\\1.txt")));
            in=new ObjectInputStream(new FileInputStream("d:\\ready\\1.txt"));

            //
            Object obj=in.readObject();
            System.out.println(obj);
            System.out.println("恭喜您！反序列化成功！");

        } catch (Exception e) {
            System.out.println("很抱歉！反序列化失败！");
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //序列化
    private static void method1() {
        ObjectOutputStream out = null;//序列化流

        try {
//            out=new ObjectOutputStream(new FileOutputStream(new File("d:\\ready\\1.txt"),true));
            out = new ObjectOutputStream(new FileOutputStream("d:\\ready\\1.txt"));

            Student obj = new Student("金帮嘉诚", 15, "中国", '男');
            //序列化
            out.writeObject(obj);
            System.out.println("恭喜您！序列化成功！");
        } catch (Exception e) {//
            System.out.println("很抱歉！序列化失败！");
            e.printStackTrace();
        } finally {//

            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
